import { WechatPayPartner } from "wechat-pay-nodejs";
import fs from "fs";

const { WX_SP_MCHID, WX_SP_MP_ID, WX_SP_KEY_V3 } = process.env;
const rootDir = process.cwd() + "/pem/" + WX_SP_MCHID;

function getPem(path) {
  const con = fs.readFileSync(rootDir + path);
  return Buffer.from(con);
}

const partner = new WechatPayPartner({
  appid: WX_SP_MP_ID, // 服务商应用ID
  mchid: WX_SP_MCHID, // 服务商户号
  cert_public_content: getPem("/apiclient_cert.pem"), // 服务商API证书内容
  cert_private_content: getPem("/apiclient_key.pem"), // 服务商API私钥内容
  user_agent: "Express-ice", // 选填
});

function checkData(data) {
  if (!data.success) {
    throw {
      msg: data.errMsg,
      code: data.errCode,
    };
  }
  return data.data || data;
}

export async function prepayJsapi(params) {
  if (!params.sub_mchid) {
    throw "未配置子商户ID";
  }
  const data = await partner.prepayJsapi(params);
  return checkData(data);
}

export function reSign(body) {
  const strToSign = [
    body.appId,
    body.timeStamp,
    body.nonceStr,
    body.package,
    "",
  ].join("\n");
  body.paySign = partner.sign(strToSign);
}

export async function createRefund(params) {
  console.log(params);
  const data = await partner.createRefund(params);
  return checkData(data);
}

export async function decryptAesGcm(params) {
  params.associatedData = params.associated_data;
  params.apiV3Key = WX_SP_KEY_V3;
  let data = await partner.decryptAesGcm(params);
  if (typeof data == "string") {
    data = JSON.parse(data);
  }
  return data;
}
